import { memo, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState } from 'react';
import { ArticleModelState, useDispatch, useSelector } from 'umi';
import ArticleList from '@/components/articleList';
import ThemeContext from '@/context/themeContext';
import initialState from '@/.umi/plugin-initial-state/models/initialState';
import React from 'react';

// 结合react class component中的shouldComponentUpdate一起记忆
const MemoArticleList = memo(ArticleList);
export default function IndexPage() {
  const {articles} = useSelector((state: {article: ArticleModelState})=>state.article);
  const dispatch = useDispatch();

  const [count, setCount] = useState(100);

  // 通过useContent直接拿到对应的context
  const theme = useContext(ThemeContext);
  // console.log('theme...', theme);

  useEffect(() => {
    dispatch({
      type: 'article/getArticleList'
    });
    // console.log('count...', count);
    setCount(10000);
    // console.log('p...', document.querySelector('p')!.innerText);
  }, []);

  // useLayoutEffect(() => {
  //   console.log('layout effect...');
  //   console.log('layout count...', count);
  //   // setCount(10000);
  // }, [count])

  interface IState{
    num: number;
  }
  interface IAction{
    readonly type: string;
    payload?: any;
  }
  // useReducer，简化版redux
  const reducer = (state: IState, action: IAction) =>{
    switch(action.type){
      case 'add': return {num: state.num+1};
      case 'sub': return {num: state.num-1};
      default: return state;
    }
  }
  /**
   * useReducer介绍
   *   const [state, dispatch] = useReducer(reducer, initialState, intializer);
   *   const [state, dispatch] = useReducer(reducer, intializer(initialState));
   */
  const [rootState, rootDispatch] = useReducer(reducer, {num: 100}, (state)=>{
    return {
      ...state,
      num: state.num*10
    }
  });

  /**
   * useRef 
   * 1. 当作全局变量存储状态
   * 2. 获取dom
   */
  const input = useRef<ImpreiveHandle>(null);
  useEffect(()=>{
    // (input.current as never as HTMLInputElement).focus();
  }, [])


  return (
    <div>
      <p placeholder="自动获取焦点">{count}</p>
      {/* <input type="text" ref={input}/> */}
      <Child ref={input}/>
      <button onClick={()=>input.current!.focus()}>获取焦点</button>
      <button onClick={()=>input.current!.setValue()}>设置value为当前时间戳</button>
      <button>清空输入框</button>

      <button onClick={()=>setCount(+new Date())}>改变count</button>
      <MemoArticleList 
        articles={articles} 
        info={useMemo(()=>({}), [])}
        // cb={useCallback(()=>{}, [])}
        cb={useMemo(()=>{
          return ()=>{}
        }, [])} 
      />
      <button onClick={()=>rootDispatch({type: 'add'})}>+</button>
      <p>{rootState.num}</p>
      <button onClick={()=>rootDispatch({type: 'sub'})}>-</button>
    </div>
  );
}


interface ImpreiveHandle extends HTMLInputElement{
  focus: ()=>void,
  setValue: ()=>void
}
const Child = React.forwardRef<HTMLInputElement>((props, ref)=>{
  const inputRef = useRef(null);
  useImperativeHandle<HTMLInputElement, ImpreiveHandle>(ref, ()=>{
    return {
      focus: ()=>(inputRef.current as never as HTMLInputElement).focus(),
      setValue: ()=>{
        (inputRef.current as never as HTMLInputElement).value = String(+new Date())
      }
    }
  })

  return <div>
    {/* <input ref={ref} type="text" placeholder="子组件的输入框"/> */}
    <input ref={inputRef} type="text" placeholder="子组件的输入框"/>
  </div>
})